package com.skivingcloud.report.datas.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.skivingcloud.report.datas.entity.ReportDatasetTransform;
import com.skivingcloud.report.datas.service.IGroovyHandler;
import com.skivingcloud.report.datas.service.TransformStrategy;

import groovy.lang.GroovyClassLoader;

@Component
public class GroovyTransformServiceImpl implements TransformStrategy {

	private static Logger log = LoggerFactory.getLogger(GroovyTransformServiceImpl.class);
	
	private GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
	
	@Override
	public String type() {
		return "javaBean";
	}

	@Override
	public List<JsonNode> transform(ReportDatasetTransform def, List<JsonNode> data) throws Exception {
		String transformScript = def.getTransformScript();
        Class<?> clazz = groovyClassLoader.parseClass(transformScript);
        if (clazz != null) {
            try {
                Object instance = clazz.newInstance();
                if (instance!=null) {
                    if (instance instanceof IGroovyHandler) {
                        IGroovyHandler handler = (IGroovyHandler) instance;
                        return handler.transform(data);
                    } else {
                        log.info("转换失败！");
                    }
                }
            } catch (Exception e) {
                log.info("执行javaBean异常", e);
                throw e;
            }
        }
        return data;
	}
    
}